﻿using BarrageGameAssistant.Core.Configs;
using BarrageGameAssistant.Core.Model;
using System.Diagnostics;

namespace BarrageGameAssistant.Core.Extensions
{
    public static class SceneExtension
    {
        /// <summary>
        /// 场景当前目录
        /// </summary>
        /// <param name="game"></param>
        /// <returns></returns>
        public static string CurrentDirectory(this Scene scene, GameProject game)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Games", $"{game.GetPlatformName()}{game.Name}", "Scenes", scene.Id);

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            return path;
        }

        /// <summary>
        /// 删除场景目录
        /// </summary>
        /// <param name="scene"></param>
        /// <returns></returns>
        public static bool DeleteDirectory(this Scene scene, GameProject game)
        {
            try
            {
                string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Games", $"{game.GetPlatformName()}{game.Name}", "Scenes", scene.Id);
                KillProcessesUsingFolder(path);
                Directory.Delete(path);
                return !Directory.Exists(path);
            }
            catch (Exception)
            {
                return false;
            }
        }

        static void KillProcessesUsingFolder(string folderPath)
        {
            foreach (var process in Process.GetProcesses())
            {
                try
                {
                    if (process.MainModule == null) continue;

                    if (!process.MainModule.FileName.StartsWith(folderPath)) continue;

                    try
                    {
                        process.Kill(); // 结束进程

                        //Console.WriteLine($"已结束进程：{process.Id}, {process.ProcessName}");
                    }
                    catch (Exception)
                    {
                        //Console.WriteLine($"无法结束进程：{process.Id}, {process.ProcessName}: {ex.Message}");
                    }
                }
                catch (Exception)
                {
                }
            }
        }
    }
}
